package cn.itcast.order.service.impl;

import cn.itcast.feign.client.ItemClient;
import cn.itcast.feign.client.UserClient;
import cn.itcast.hmall.dto.common.ResultDTO;
import cn.itcast.hmall.dto.common.ThreadLocalUtil;
import cn.itcast.hmall.dto.order.OrderReqDTO;
import cn.itcast.hmall.pojo.item.Item;
import cn.itcast.hmall.pojo.order.Order;
import cn.itcast.hmall.pojo.order.OrderDetail;
import cn.itcast.hmall.pojo.order.OrderLogistics;
import cn.itcast.hmall.pojo.user.Address;
import cn.itcast.hmall.pojo.user.User;
import cn.itcast.order.mapper.OrderDetailMapper;
import cn.itcast.order.mapper.OrderLogisticsMapper;
import cn.itcast.order.mapper.OrderMapper;
import cn.itcast.order.service.OrderService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;

/**
 * @author oldwine
 * @date 2022/6/22
 * @Version 1.0
 */
@Service
@Transactional
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    @Autowired
    private ItemClient itemClient;
    @Autowired
    private UserClient userClient;

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private OrderLogisticsMapper orderLogisticsMapper;

    /**
     * 创建订单方法
     *
     * @param vo 封装的参数对象
     * @return 返回订单id
     */
    @Override
    public String createOrder(OrderReqDTO vo) {
        //1.获vo对象中的 商品购买数据num 和商品id
        Integer num = vo.getNum();
        Integer paymentType = vo.getPaymentType();
        Long addressId = vo.getAddressId();
        Long itemId = vo.getItemId();

        //TODO:创建订单表
        //2.远程调用 根据商品id查询商品获取商品信息 (实际上是需要获取商品的价格进行计算)
        Item item = itemClient.getItemById(itemId);
        Long price = item.getPrice();
        Long totalFee = num * price;

        //3.封装数据
        Order order = Order.builder().totalFee(totalFee)
                .paymentType(paymentType)
                .userId(ThreadLocalUtil.getUserId())
                .status(1)
                .updateTime(new Date())
                .build();
        orderMapper.insert(order); //自动回填订单id到该对象中
        Long orderId = order.getId();

        //TODO:创建订单详情表
        String name = item.getName();//商品标题
        String spec = item.getSpec(); //商品动态属性健康值
        String image = item.getImage();//商品图片
        OrderDetail orderDetail = OrderDetail.builder()
                .orderId(orderId)
                .itemId(itemId)
                .num(num)
                .name(name)
                .spec(spec)
                .price(price)
                .image(image)
                .build();
        orderDetailMapper.insert(orderDetail);

        //TODO:创建物流详情表
        //根据当前地址id远程调用用户微服务获取用户地址信息
        Address address = userClient.getAddress(addressId);
        String contact = address.getContact();//收件人
        String mobile = address.getMobile();//收件人手机号码
        String province = address.getProvince();//省
        String city = address.getCity();//市
        String town = address.getTown();//区
        String street = address.getStreet();//街道

        OrderLogistics orderLogistics = OrderLogistics.builder()
                .orderId(orderId)
                .contact(contact)
                .mobile(mobile)
                .province(province)
                .city(city)
                .town(town)
                .street(street).build();
        orderLogisticsMapper.insert(orderLogistics);
        return orderId.toString();
    }

    /**
     * 订单支付功能
     * @param orderId 订单id
     * @param password 用户输入密码
     * @return 返回结果
     */
    @Override
    public ResultDTO payOrder(Long orderId, String password) {
        User object = JSON.parseObject(password, User.class);
        String payPassword = object.getPassword();
        //1.根据订单id查询订单信息
        Order order = orderMapper.selectById(orderId);
        Integer status = order.getStatus();
        //2.检查订单状态 如果订单状态为 1 继续支付
        if (status != 1) {
            return ResultDTO.error("已支付");
        }
        //获取当前用户的id
        Long userId = ThreadLocalUtil.getUserId();
        User user = userClient.queryUserById(userId);

//        //密码校验
        if (!DigestUtils.md5DigestAsHex(payPassword.getBytes()).equals(user.getPassword())) {
            return ResultDTO.error("密码错误");
        }

        //用户余额校验
        if (user.getBalance() < order.getTotalFee()) {
            return ResultDTO.error("余额不足");
        }

        //执行支付功能
        Boolean flag = userClient.payMoney(order.getTotalFee(), userId);
        if (!flag) {
            return ResultDTO.error("支付失败");
        }

        //支付成功后 修改商品库存
        LambdaQueryWrapper<OrderDetail> wrapper = Wrappers.lambdaQuery(OrderDetail.class);
        wrapper.eq(OrderDetail::getOrderId,orderId);
        OrderDetail orderDetail = orderDetailMapper.selectOne(wrapper);
        itemClient.substractStock(orderDetail.getItemId(),orderDetail.getNum());

        //更新订单状态和订单时间
        order.setStatus(2);
        order.setPayTime(new Date());
        orderMapper.updateById(order);
        return ResultDTO.ok();
    }
}
